package com.socool.sinofaith.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.adapter.TaskAddressAdapter;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifQuestionOptionsDao;
import com.socool.sinofaith.dao.SifSubTaskDao;
import com.socool.sinofaith.dao.SifSubTemplateDao;
import com.socool.sinofaith.dao.SifTaskAddressDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.dao.SifTaskQuestionDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.AnswerReq;
import com.socool.sinofaith.model.BaseMessage;
import com.socool.sinofaith.model.DownloadTaskMessage;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.QuestionAnswerReqBean;
import com.socool.sinofaith.model.SifQuestionOptionsBean;
import com.socool.sinofaith.model.SifSubTaskBean;
import com.socool.sinofaith.model.SifSubTemplateBean;
import com.socool.sinofaith.model.SifTaskAddressBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.SifTaskQuestionBean;
import com.socool.sinofaith.model.Task;
import com.socool.sinofaith.model.UpLoadFileBean;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.S;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;
import com.socool.sinofaith.view.MyDialog;
import com.socool.sinofaith.view.MyListView;
import com.socool.sinofaith.view.ProgressDialog;
import com.socool.sinofaith.view.TiPsDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

/**
 * 任务详情Activity
 * 
 * @author YD
 * 
 */
public class TaskDetailActivity extends BaseActivity
		implements CenterViewFactory, SpinnerViewFactory, View.OnClickListener {

	ActionBarHelperBase mActionBarHelperBase;
	private Task mTask;
	private TextView myTaskNameTextView, taskNameTextView, startTimeTextView, endTimeTextView, taskDescTextView;
	private Button btn_submit;
	private MyListView addressListView;
	private TaskAddressAdapter mTaskAddressAdapter;
	private Button btn_downloadTask;

	private SifTaskDao taskDao;
	private SifTaskAddressDao taskAddressDao;
	private SifSubTaskDao subTaskDao;
	private SifSubTemplateDao subTemplateDao;
	private SifTaskQuestionDao taskQuestionDao;
	private SifQuestionOptionsDao questionOptionsDao;
	private QuestionAnswerDao answerDao;
	private LoadingDialog mLoadingDialog;
	// 定位相关
	LocationClient mLocClient;
	boolean isFirstLoc = true;// 是否首次定位
	public MyLocationListenner myListener;
	private boolean isPublicTask = false; // true为公共任务
	private Button rushTaskButton;
	private Button startTaskButton;
	private Button giveupTaskButton;
	private LatLng mLatLng;

	private MyDialog.Builder builder;
	private Dialog dialog;
	private TiPsDialog mTiPsDialog;
	private ProgressDialog pDialog;

	private ArrayList<UpLoadFileBean> upInfos;
	private String userMobile;
	private HashMap<String, Integer> answerMap = new HashMap<String, Integer>();

	private int qCount;

	int success;
	int sum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_taskdetail);
		SocoolApplication.addActivity(this);
		mTiPsDialog = new TiPsDialog(this, R.style.dialog, null, "离线登录状态下该功能不可用");
		mLoadingDialog = new LoadingDialog(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);
		mActionBarHelperBase.setmClickListener(this);
		pDialog = new ProgressDialog(this, "正在提交中");

		taskNameTextView = (TextView) findViewById(R.id.taskNameTextView);
		myTaskNameTextView = (TextView) findViewById(R.id.myTaskNameTextView);
		startTimeTextView = (TextView) findViewById(R.id.startTimeTextView);
		endTimeTextView = (TextView) findViewById(R.id.endTimeTextView);
		taskDescTextView = (TextView) findViewById(R.id.taskDescTextView);
		addressListView = (MyListView) findViewById(R.id.addressListView);
		rushTaskButton = (Button) findViewById(R.id.rushTaskButton);
		startTaskButton = (Button) findViewById(R.id.startTaskButton);
		giveupTaskButton = (Button) findViewById(R.id.btn_giveupTask);
		btn_submit = (Button) findViewById(R.id.btn_submit_taskdetail);

		mTask = (Task) this.getIntent().getSerializableExtra("task");
		taskNameTextView.setText(mTask.getTaskName());
		myTaskNameTextView.setText(mTask.getTaskName());
		startTimeTextView.setText(mTask.getStartTM());
		endTimeTextView.setText(mTask.getEndTM());
		taskDescTextView.setText(Html.fromHtml(mTask.getTaskDesc()));

		btn_downloadTask = (Button) findViewById(R.id.btn_downloadTask);
		btn_downloadTask.setOnClickListener(this);
		rushTaskButton.setOnClickListener(this);
		startTaskButton.setOnClickListener(this);
		giveupTaskButton.setOnClickListener(this);

		userMobile = getSPString();
		btn_submit.setOnClickListener(this);
		// if (mTask.getIsPublic() != null && mTask.getIsPublic().equals("0")) {
		// btn_downloadTask.setVisibility(View.VISIBLE);
		// rushTaskButton.setVisibility(View.GONE);
		// } else {
		// rushTaskButton.setVisibility(View.VISIBLE);
		// }
		if ("1".equals(mTask.getIsPublic())) {
			rushTaskButton.setVisibility(View.VISIBLE);
		} else {
			btn_downloadTask.setVisibility(View.VISIBLE);
			rushTaskButton.setVisibility(View.GONE);
		}

		mTaskAddressAdapter = new TaskAddressAdapter(this, isPublicTask);
		mTaskAddressAdapter.addDatas(mTask.getTaskAddress());
		addressListView.setAdapter(mTaskAddressAdapter);

		taskDao = new SifTaskDao(TaskDetailActivity.this);
		taskAddressDao = new SifTaskAddressDao(TaskDetailActivity.this);
		subTaskDao = new SifSubTaskDao(TaskDetailActivity.this);
		subTemplateDao = new SifSubTemplateDao(TaskDetailActivity.this);
		taskQuestionDao = new SifTaskQuestionDao(TaskDetailActivity.this);
		questionOptionsDao = new SifQuestionOptionsDao(TaskDetailActivity.this);
		answerDao = new QuestionAnswerDao(this);

		List<SifTaskBean> tasklist = taskDao.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID="
				+ mTask.getTask_ID() + " and Mobile=" + userMobile);
		if (null != tasklist && tasklist.size() > 0) {
			if (mTaskAddressAdapter.getMdatas().size() == 0) {
				startTaskButton.setVisibility(View.VISIBLE);
			} else {
				mTaskAddressAdapter.setShowStartTask(true);
				mTaskAddressAdapter.notifyDataSetChanged();
			}
			btn_downloadTask.setEnabled(false);
		} else {
			mTaskAddressAdapter.setShowStartTask(false);
			mTaskAddressAdapter.notifyDataSetChanged();
			btn_downloadTask.setEnabled(true);
		}

		// 定位初始化
		mLocClient = new LocationClient(this);
		myListener = new MyLocationListenner();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		builder = new MyDialog.Builder(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("TAG", mTask.toString());

		if (mTask.getIsPublic() != null && mTask.getIsPublic().equals("1")
				&& !TextUtils.isEmpty(mTask.getGetTaskTime())) {
			btn_downloadTask.setVisibility(View.VISIBLE);
			rushTaskButton.setVisibility(View.GONE);
			new AsyncTask<Void, Void, Boolean>() {
				@Override
				protected Boolean doInBackground(Void... arg0) {
					QuestionAnswerDao questionAnswerDao = new QuestionAnswerDao(TaskDetailActivity.this);
					ArrayList<QuestionAnswerBean> finshList = questionAnswerDao
							.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where IsFinish=2"
									+ " and Task_ID=" + mTask.getTask_ID() + " and Submiter=" + userMobile);
					if (finshList.size() > 0) {
						return false;

					}

					ArrayList<QuestionAnswerBean> list = questionAnswerDao
							.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where IsFinish<>2"
									+ " and Task_ID=" + mTask.getTask_ID() + " and Submiter=" + userMobile);
					if (list.size() > 0)
						return true;
					ArrayList<QuestionAnswerBean> alllist = questionAnswerDao
							.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where  Task_ID="
									+ mTask.getTask_ID() + " and Submiter=" + userMobile);
					if (alllist.size() == 0)
						return true;

					return false;
				}

				@Override
				protected void onPostExecute(Boolean result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					if (result) {
						giveupTaskButton.setVisibility(View.VISIBLE);
					} else {
						giveupTaskButton.setVisibility(View.GONE);
					}
				}

			}.execute();

		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btn_downloadTask:
			builder.setTitle("温馨提示").setMessage("确定下载当前任务？")
					.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							downloadTask();
							dialog.dismiss();
						}
					}).setNegativeButton("关闭", new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog = builder.create();
			dialog.show();
			break;
		case R.id.rushTaskButton:
			fetchTask();
			break;
			
		case R.id.startTaskButton:
			Intent intent = new Intent(this, SubTaskActivity.class);
			intent.putExtra("taskid", mTask.getTask_ID());
			SifTaskDao dao = new SifTaskDao(this);
			ArrayList<SifTaskBean> query = dao.query(mTask.getTask_ID());
			if (query.size() > 0)
				startActivity(intent);
			else
				Toast.makeText(this, "数据错误,请重新下拉刷新", 1).show();
			break;

		case R.id.btn_giveupTask:

			if (!((SocoolApplication) TaskDetailActivity.this.getApplication()).isOffLineLogin()) {
				builder.setTitle("温馨提示").setMessage("确定取消当前任务？")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								giveupTask();
								dialog.dismiss();
							}
						}).setNegativeButton("关闭", new android.content.DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				dialog = builder.create();
				dialog.show();
			} else {
				mTiPsDialog.show();
			}

			break;

		case R.id.btn_submit_taskdetail:

			taskid = mTask.getTask_ID();

			sum = S.getFileNum(this, userMobile, taskid, null, null);
			success = 0;
			recursionAnswer();
			// // 获取可以提交的Stemp集合
			// String searchAnswerSql = "select * from "
			// + QuestionAnswerBean.TABLENAME + " as answer join "
			// + SifTaskQuestionBean.TABLENAME
			// + " as question on answer.Task_ID=question.Task_ID and"
			// + " answer.TaskQuestion_ID=question.TaskQuestion_ID "
			// + "where answer.Task_ID='" + mTask.getTask_ID()
			// + "' and Stemp_ID in (select Stemp_ID from "
			// + SifSubTemplateBean.TABLENAME + " where Task_ID='"
			// + mTask.getTask_ID() + "') and Submiter='"
			// + SinofaithUtil.userInfo.getUserMobile()
			// + "' and answer.IsFinish='1' group by answer.Stemp_ID";
			//
			// answerList = answerDao.queryBySql(searchAnswerSql);
			// Log.i("TAG", "answerList.size" + answerList.size());
			// answersCount = answerList.size();
			// answersErrorCount = 0;
			// answerMap.clear();
			//
			// if (null != answerList && answerList.size() > 0) {
			//
			// for (int i = 0; i < answerList.size(); i++) {
			// final QuestionAnswerBean answerBean = answerList.get(i);
			//
			// answerMap.put(answerBean.getStemp_ID(), 0);
			// new Handler().post(new Runnable() {
			//
			// @Override
			// public void run() {
			// Log.i("TAG", answerBean.getStemp_ID() + " run "
			// + answerBean.getTemplate());
			// submitAnswers(answerBean);
			//
			// }
			// });
			//
			// }
			// } else {
			// Toast.makeText(this, "尚且不可提交", 0).show();
			// }
			// break;

		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	void downloadTask() {
		Toast.makeText(TaskDetailActivity.this, "开始缓存数据", Toast.LENGTH_LONG).show();
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.downloadTask_url);
		params.put("did", SinofaithUtil.did);
		params.put("taskid", mTask.getTask_ID());

		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				try {
					// Toast.makeText(TaskDetailActivity.this, t.toString(),
					// Toast.LENGTH_LONG).show();
					final DownloadTaskMessage downloadTaskMessage = HttpJsonAdapter.getInstance().get(t.toString(),
							DownloadTaskMessage.class);
					if (downloadTaskMessage.getResult().equals("0")) {
						// 将任务保存至本地
						btn_downloadTask.setEnabled(false);

						new AsyncTask<Void, Void, Boolean>() {

							@Override
							protected Boolean doInBackground(Void... arg0) {
								String taskid = "";
								if (null != downloadTaskMessage.getSif_Task()
										&& downloadTaskMessage.getSif_Task().size() > 0) {
									for (int i = 0; i < downloadTaskMessage.getSif_Task().size(); i++) {
										SifTaskBean taskBean = downloadTaskMessage.getSif_Task().get(i);
										taskBean.setMobile(userMobile);
										Date date = new Date();
										SimpleDateFormat datematter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
										taskBean.setCreateTime(datematter.format(date));
										taskid = taskBean.getTask_ID();
										List<SifTaskBean> tasklist = taskDao
												.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID="
														+ taskBean.getTask_ID() + " and Mobile=" + userMobile);
										if (null == tasklist || tasklist.size() <= 0) {
											taskDao.insert(taskBean);
										}
									}
								}
								if (null != downloadTaskMessage.getSif_TaskAddress()
										&& downloadTaskMessage.getSif_TaskAddress().size() > 0) {
									for (int i = 0; i < downloadTaskMessage.getSif_TaskAddress().size(); i++) {
										SifTaskAddressBean addressBean = downloadTaskMessage.getSif_TaskAddress()
												.get(i);
										List taskAddressList = taskAddressDao.queryBySql("select * from "
												+ SifTaskAddressBean.TABLENAME + " where TaskAddress_ID="
												+ addressBean.getTaskAddress_ID() + " and Task_ID=" + taskid);
										if (null == taskAddressList || taskAddressList.size() <= 0) {
											taskAddressDao.insert(addressBean);
										}
									}
								}
								// 缓存二级任务
								String subtaskid = "";
								if (null != downloadTaskMessage.getSif_SubTask()
										&& downloadTaskMessage.getSif_SubTask().size() > 0) {
									for (int i = 0; i < downloadTaskMessage.getSif_SubTask().size(); i++) {
										SifSubTaskBean subTaskBean = downloadTaskMessage.getSif_SubTask().get(i);
										subtaskid = subTaskBean.getSubTask_ID();
										List subTaskList = subTaskDao.queryBySql(
												"select * from " + SifSubTaskBean.TABLENAME + " where SubTask_ID="
														+ subTaskBean.getSubTask_ID() + " and Task_ID=" + taskid);
										if (null == subTaskList || subTaskList.size() <= 0) {
											subTaskDao.insert(subTaskBean);
										}

										/**
										 * 
										 * 
										 * 
										 * 
										 * 这里做个标记
										 * 
										 * 
										 */
										// 缓存模板(车架号)数据
										if (null != downloadTaskMessage.getSif_SubTemplate()
												&& downloadTaskMessage.getSif_SubTemplate().size() > 0) {
											boolean m = false;
											for (int n = 0; n < downloadTaskMessage.getSif_SubTemplate().size(); n++) {
												SifSubTemplateBean subTemplateBean = downloadTaskMessage
														.getSif_SubTemplate().get(n);
												subTemplateBean.setTask_ID(mTask.getTask_ID());
												List subTemplateList = subTemplateDao
														.queryBySql("select * from " + SifSubTemplateBean.TABLENAME
																+ " where Stemp_ID=" + subTemplateBean.getStemp_ID()
																+ " and SubTask_ID=" + subTaskBean.getSubTask_ID());
												// 判断数据库是否有同一道题目
												if (null == subTemplateList || subTemplateList.size() <= 0) {
													subTemplateBean.setIsMark("0");

													subTemplateDao.insert(subTemplateBean);
												}

											}
										}

										// if(subTaskBean.getHasChild().equals("0")){
										// 缓存题目数据
										if (null != downloadTaskMessage.getSif_TaskQuestion()
												&& downloadTaskMessage.getSif_TaskQuestion().size() > 0) {

											for (int j = 0; j < downloadTaskMessage.getSif_TaskQuestion().size(); j++) {
												SifTaskQuestionBean taskQuestionBean = downloadTaskMessage
														.getSif_TaskQuestion().get(j);
												taskQuestionBean.setTask_ID(mTask.getTask_ID());
												List taskQuestionList = taskQuestionDao.queryBySql("select * from "
														+ SifTaskQuestionBean.TABLENAME + " where TaskQuestion_ID="
														+ taskQuestionBean.getTaskQuestion_ID() + " and Template_ID="
														+ subTaskBean.getTemplate_ID() + " and Task_ID="
														+ mTask.getTask_ID());
												if (null == taskQuestionList || taskQuestionList.size() <= 0) {
													taskQuestionDao.insert(taskQuestionBean);
												}
											}

											for (int j = 0; j < downloadTaskMessage.getSif_TaskQuestion().size(); j++) {
												SifTaskQuestionBean taskQuestionBean = downloadTaskMessage
														.getSif_TaskQuestion().get(j);
												taskQuestionBean.setTask_ID(mTask.getTask_ID());
												List taskQuestionList = taskQuestionDao.queryBySql("select * from "
														+ SifTaskQuestionBean.TABLENAME + " where TaskQuestion_ID="
														+ taskQuestionBean.getTaskQuestion_ID() + " and Template_ID="
														+ subTaskBean.getTemplate_ID() + " and Task_ID="
														+ mTask.getTask_ID());
												if (null != taskQuestionList && taskQuestionList.size() > 0) {
													for (int k = 0; k < taskQuestionList.size(); k++) {
														SifTaskQuestionBean questionBean = (SifTaskQuestionBean) taskQuestionList
																.get(k);
														// 缓存题目选项
														if (null != downloadTaskMessage.getSif_QuestionOptions()
																&& downloadTaskMessage.getSif_QuestionOptions()
																		.size() > 0) {
															for (int m = 0; m < downloadTaskMessage
																	.getSif_QuestionOptions().size(); m++) {
																SifQuestionOptionsBean questionOptionsBean = downloadTaskMessage
																		.getSif_QuestionOptions().get(m);
																questionOptionsBean.setTask_ID(mTask.getTask_ID());
																List questionOptionsList = questionOptionsDao
																		.queryBySql("select * from "
																				+ SifQuestionOptionsBean.TABLENAME
																				+ " where OP_ID="
																				+ questionOptionsBean.getOP_ID()
																				+ " and TaskQuestion_ID="
																				+ questionBean.getTaskQuestion_ID()
																				+ " and Task_ID=" + mTask.getTask_ID());
																if (null == questionOptionsList
																		|| questionOptionsList.size() <= 0) {
																	questionOptionsDao.insert(questionOptionsBean);
																}
															}
														}
													}
												}
											}
										}
										// }
									}
								}

								return null;
							}

							@Override
							protected void onPostExecute(Boolean result) {
								// TODO Auto-generated method stub
								super.onPostExecute(result);
								if (mTaskAddressAdapter.getMdatas().size() == 0) {
									startTaskButton.setVisibility(View.VISIBLE);
								} else {
									mTaskAddressAdapter.setShowStartTask(true);
									mTaskAddressAdapter.notifyDataSetChanged();
								}
								// Toast.makeText(
								// TaskDetailActivity.this,
								// taskDao.query("1").get(0).getTaskName()
								// + "", Toast.LENGTH_LONG).show();
								mLoadingDialog.dismiss();
							}
						}.execute();

						// taskDao.query(null);

					} else {
						Toast.makeText(TaskDetailActivity.this, downloadTaskMessage.getDesc(), Toast.LENGTH_LONG)
								.show();
						mLoadingDialog.dismiss();
					}
				} catch (Exception e) {
					Toast.makeText(TaskDetailActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
					mLoadingDialog.dismiss();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(TaskDetailActivity.this, strMsg, Toast.LENGTH_LONG).show();
				mLoadingDialog.dismiss();
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {

		TextView tv = new TextView(this);
		tv.setText("任务详情");
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View createSpinnerView() {
		ImageView imageview = new ImageView(this);
		return imageview;
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
			if (isFirstLoc) {

				isFirstLoc = false;
				mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
				SinofaithUtil.GPS = location.getLatitude() + "," + location.getLongitude();
				mTaskAddressAdapter.setLocalLatLng(mLatLng);
				mTaskAddressAdapter.notifyDataSetChanged();

			}
		}

		public void onReceivePoi(BDLocation poiLocation) {

		}

	}

	@SuppressWarnings("unchecked")
	public void fetchTask() {

		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.fetchtask_url);
		params.put("did", SinofaithUtil.did);
		params.put("mobile", userMobile);
		params.put("taskid", mTask.getTask_ID());

		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				mLoadingDialog.dismiss();
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						Toast.makeText(TaskDetailActivity.this, baseMessage.getDesc(), Toast.LENGTH_SHORT).show();
						btn_downloadTask.setVisibility(View.VISIBLE);
						giveupTaskButton.setVisibility(View.VISIBLE);
						rushTaskButton.setVisibility(View.INVISIBLE);
						Date date = new Date();
						SimpleDateFormat datematter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						mTask.setGetTaskTime(datematter.format(date));
					} else {
						Toast.makeText(TaskDetailActivity.this, baseMessage.getDesc(), Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				mLoadingDialog.dismiss();
			}

		});

	}

	// 取消任务
	@SuppressWarnings("unchecked")
	public void giveupTask() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", "giveupTask");
		params.put("did", SinofaithUtil.did);
		params.put("mobile", userMobile);
		params.put("taskid", mTask.getTask_ID());

		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				mLoadingDialog.dismiss();
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						Toast.makeText(TaskDetailActivity.this, baseMessage.getDesc(), Toast.LENGTH_SHORT).show();
						btn_downloadTask.setVisibility(View.INVISIBLE);
						giveupTaskButton.setVisibility(View.INVISIBLE);
						startTaskButton.setVisibility(View.INVISIBLE);
						rushTaskButton.setVisibility(View.VISIBLE);
						mTask.setGetTaskTime(null);
						mTaskAddressAdapter.setShowStartTask(false);
						mTaskAddressAdapter.notifyDataSetChanged();
						QuestionAnswerDao questionAnswerDao = new QuestionAnswerDao(TaskDetailActivity.this);
						SifTaskDao sifTaskDao = new SifTaskDao(TaskDetailActivity.this);
						SifQuestionOptionsDao sifQuestionOptionsDao = new SifQuestionOptionsDao(
								TaskDetailActivity.this);
						SifSubTaskDao sifSubTaskDao = new SifSubTaskDao(TaskDetailActivity.this);
						SifSubTemplateDao sifSubTemplateDao = new SifSubTemplateDao(TaskDetailActivity.this);
						SifTaskAddressDao sifTaskAddressDao = new SifTaskAddressDao(TaskDetailActivity.this);
						SifTaskQuestionDao sifTaskQuestionDao = new SifTaskQuestionDao(TaskDetailActivity.this);
						questionAnswerDao.deleteByTaskId(mTask.getTask_ID());
						sifTaskDao.deleteByTaskId(mTask.getTask_ID());
						sifQuestionOptionsDao.deleteByTaskId(mTask.getTask_ID());
						sifSubTaskDao.deleteByTaskId(mTask.getTask_ID());
						sifSubTemplateDao.deleteByTaskId(mTask.getTask_ID());
						sifTaskAddressDao.deleteByTaskId(mTask.getTask_ID());
						sifTaskQuestionDao.deleteByTaskId(mTask.getTask_ID());

					} else {
						Toast.makeText(TaskDetailActivity.this, baseMessage.getDesc(), Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				mLoadingDialog.dismiss();
			}

		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
	}

	// private int count = 0;
	// private int totalcount = 0;
	private String tempjson = "";
	private String taskid = "";
	private Toast mToast;

	public void showToast(String text) {
		if (mToast == null) {
			mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(text);
			mToast.setDuration(Toast.LENGTH_SHORT);
		}
		mToast.show();
	}

	private ArrayList<QuestionAnswerBean> answerList;

	private void submitDeal(boolean norm) {
		if (norm) {

			if (answerList != null) {
				// 当只有一道题提交时
				if (answerList.size() == 1 && qCount == 0) {
					showToast("提交成功");
					pDialog.dismiss();
					getUploadCheck();
				}
				// 大于1时
				else if (answerList.size() > 1) {
					pDialog.setText("正在提交,剩余" + (answerList.size() - 1) + "未提交");
					if (qCount == 0) {
						// 递归提交
						recursionAnswer();
					} else {
						// 继续执行

					}
				}

			}
		} else {
			pDialog.dismiss();
			showToast("提交失败,剩余" + (answerList.size() - 1) + "未提交");
		}
	}

	private void recursionAnswer() {
		String searchAnswerSql = "select * from " + QuestionAnswerBean.TABLENAME + " as answer join "
				+ SifTaskQuestionBean.TABLENAME + " as question on answer.Task_ID=question.Task_ID  and"
				+ " answer.TaskQuestion_ID=question.TaskQuestion_ID " + "where answer.Task_ID='" + mTask.getTask_ID()
				+ "' and Stemp_ID in (select Stemp_ID from " + SifSubTemplateBean.TABLENAME + " where Task_ID='"
				+ mTask.getTask_ID() + "') and Submiter='" + userMobile
				+ "' and answer.IsFinish='1'  group by answer.Stemp_ID";

		qCount = 0;
		answerList = answerDao.queryBySql(searchAnswerSql);
		pDialog.show();
		Log.i("TAG", answerList.size() + "     ");
		if (answerList != null && answerList.size() > 0) {
			final QuestionAnswerBean bean = answerList.get(0);

			new Thread(new Runnable() {

				@Override
				public void run() {
					submit(bean);

				}
			}).start();
		} else {
			pDialog.dismiss();
			getUploadCheck();
		}

	}

	/**
	 * 提交完一道题后更新本地数据
	 */
	public void afterSubmitUpdateLocalData(final String subTaskID, final String stempID) {
		QuestionAnswerDao answerDao = new QuestionAnswerDao(TaskDetailActivity.this);
		String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
				+ subTaskID;
		if (null != stempID && !"".equals(stempID)) {
			sql += " and Stemp_ID=" + stempID;
		}
		sql += " and Submiter=" + userMobile;
		List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				QuestionAnswerBean answerBean = answerlist.get(i);
				answerBean.setIsFinish("2");
				answerDao.update(answerBean);
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void submit(final QuestionAnswerBean bean) {
		upInfos = new ArrayList<UpLoadFileBean>();
		final String subTaskID = bean.getSubTask_ID();
		final String stempID = bean.getStemp_ID();
		final QuestionAnswerReqBean answerReqBean = new QuestionAnswerReqBean();
		answerReqBean.setTask_ID(taskid);
		answerReqBean.setSubmiter(userMobile);
		answerReqBean.setStemp_ID(bean.getStemp_ID());
		answerReqBean.setSubTask_ID(bean.getSubTask_ID());

		ArrayList<QuestionAnswerBean> answer = answerDao.queryBySql(
				"select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid + "' and SubTask_ID='"
						+ subTaskID + "' and Stemp_ID='" + bean.getStemp_ID() + "' and Submiter='" + userMobile + "'");

		ArrayList<AnswerReq> SubAnswer = new ArrayList<AnswerReq>();

		if (null != answer && answer.size() > 0) {
			// 把拉出的对应的StempID答案嫁到SubAnswer中
			for (int i = 0; i < answer.size(); i++) {
				QuestionAnswerBean answerBean = answer.get(i);
				AnswerReq answerReq = new AnswerReq();
				answerReq.setAnswer(answerBean.getAnswer());
				answerReq.setFileCount(answerBean.getFileCount());
				answerReq.setOtherAnswer(answerBean.getOtherAnswer());
				answerReq.setTaskQuestion_ID(answerBean.getTaskQuestion_ID());
				ArrayList<SifTaskQuestionBean> questionBeans = taskQuestionDao
						.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='"
								+ bean.getTemplate() + "' and TaskQuestion_ID=" + answerBean.getTaskQuestion_ID());
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(0);
				answerReq.setQuestion(taskQuestionBean.getQuestion());
				answerReq.setQuestionType(taskQuestionBean.getQuestionType());
				answerReq.setOrder(taskQuestionBean.getOrderIndex());
				answerReq.setGPS(answerBean.getGPS());
				answerReq.setGPSTime(answerBean.getGPSTime());
				SubAnswer.add(answerReq);
			}
		}

		answerReqBean.setSubAnswer(SubAnswer);
		if (null != answerReqBean.getSubAnswer() && answerReqBean.getSubAnswer().size() > 0) {
			for (int i = 0; i < answerReqBean.getSubAnswer().size(); i++) {
				AnswerReq answerReq = answerReqBean.getSubAnswer().get(i);
				if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
						&& !"0".equals(answerReq.getFileCount())) {
					for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
						qCount++;
					}
				}
			}
		}
		try {
			tempjson = HttpJsonAdapter.getInstance().toJson(answerReqBean);
			Log.v("qqqq", tempjson);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadAnswer_url);
		params.put("did", SinofaithUtil.did);
		params.put("dajson", tempjson);
		// 没有文件.提交answer传1
		if (qCount == 0) {
			params.put("taskfinally", "1");
		}

		fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();

			}

			@Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// mLoadingDialog.dismiss();
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {

						// 没有文件
						if (qCount == 0) {
							afterSubmitUpdateLocalData(subTaskID, stempID);
							submitDeal(true);
						}
						// 有文件
						else {
							ArrayList<AnswerReq> answerReqs = answerReqBean.getSubAnswer();
							// answerReqs 每个题目的答案集合
							if (null != answerReqs && answerReqs.size() > 0) {
								for (int i = 0; i < answerReqs.size(); i++) {
									Log.i("TAG", "answerreqs" + answerReqs.size());
									AnswerReq answerReq = answerReqs.get(i);
									if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
											&& !"0".equals(answerReq.getFileCount())) {
										String[] temps = answerReq.getAnswer().split("#");
										// 车架号下面一个题目的文件提交
										for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
											Log.v("qqqq", temps[j]);
											if (null != temps[j] && !"".equals(temps[j])) {
												File file = new File(temps[j]);
												String fileName = file.getName();
												String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
														fileName.length());
												// 问题类型
												String qtype = "1";
												if ("3".equals(answerReq.getQuestionType())) {
													qtype = "1";
												} else if ("4".equals(answerReq.getQuestionType())) {
													qtype = "2";
												} else {
													qtype = "3";
												}
												UpLoadFileBean upBean = new UpLoadFileBean();
												upBean.setFile(file);
												upBean.setFileType(fileType);
												upBean.setGps(answerReq.getGPS());
												upBean.setOrder(answerReq.getOrder());
												upBean.setOtherAnswer(answerReq.getOtherAnswer());
												upBean.setqType(qtype);
												upBean.setStempId(stempID);
												upBean.setSubTaskId(subTaskID);
												upBean.setTaskId(taskid);
												upBean.setTaskQuestionId(answerReq.getTaskQuestion_ID());
												upInfos.add(upBean);

											}
										}
									}
								}
								upFileIterator();
							} else {
								submitDeal(false);
							}
						}

					} else {
						submitDeal(false);

					}
				} catch (Exception e) {
					submitDeal(false);
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				submitDeal(false);
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(TaskDetailActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}

		});

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void uploadFiles(final String taskid, final String subtaskid, final String tempid, final String questionid,
			final String ftype, final String suffix, final String order, final String desc, final File file,
			final String GPS) {

		FinalHttp fh = new FinalHttp();
		final AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadFile_url);
		params.put("did", SinofaithUtil.did);
		params.put("taskid", taskid);
		params.put("subtaskid", subtaskid);
		params.put("tempid", tempid);
		params.put("questionid", questionid);
		params.put("mobile", userMobile);
		params.put("ftype", ftype);
		params.put("suffix", suffix);
		params.put("order", order);
		params.put("desc", desc);
		params.put("finally", "0");
		if (qCount == 1) {
			params.put("taskfinally", "1");
		}
		params.put("GPS", GPS);
		try {
			S.FileParams(this, params, file);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + "?" + params);
		fh.post(ConstansJsonUrl.REQUEST_URL, null, params, null, new AjaxCallBack() {
			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					Log.i("TAG", "upfile  " + baseMessage.getResult());
					if (baseMessage.getResult().equals("0")) {

						qCount--;
						success++;
						if (qCount == 0) {
							QuestionAnswerDao answerDao = new QuestionAnswerDao(TaskDetailActivity.this);
							Log.i("TAG", baseMessage.getDesc() + " upfile");
							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							if (null != tempid && !"".equals(tempid)) {
								sql += " and Stemp_ID=" + tempid;
							}
							sql += " and Submiter=" + userMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}
							submitDeal(true);
						} else {
							if (upInfos != null && upInfos.size() > 0) {
								upInfos.remove(0);
								upFileIterator();
							}
						}
					} else {
						Log.i("TAG", "uploadfile else error");
						submitDeal(false);
					}
				} catch (Exception e) {
					Log.i("TAG", "uploadfile catch error");
					submitDeal(false);
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				submitDeal(false);
				Log.i("TAG", "uploadfile  onfailed");
				super.onFailure(t, errorNo, strMsg);
			}

		});
	}

	private void getUploadCheck() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", "uploadAnswerCheck");
		params.put("did", SinofaithUtil.did);
		params.put("mobile", userMobile);
		params.put("taskid", mTask.getTask_ID());

		fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack<Object>() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}

			@Override
			public void onSuccess(Object t) {
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);

					if (baseMessage.getResult().equals("0")) {

						String temps = baseMessage.getDesc();
						if (temps != null && temps.length() > 0) {
							String[] stemps = temps.split(",");
							for (int i = 0; i < stemps.length; i++) {
								String stemp = stemps[i];
								QuestionAnswerDao answerDao = new QuestionAnswerDao(TaskDetailActivity.this);
								String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID="
										+ taskid;
								if (null != stemp && !"".equals(stemp)) {
									sql += " and Stemp_ID=" + stemp;
								}
								sql += " and Submiter=" + userMobile;
								List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);

								if (null != answerlist && answerlist.size() > 0) {
									showToast("已修复错误提交,请重新提交!");
									for (int j = 0; j < answerlist.size(); j++) {
										QuestionAnswerBean answerBean = answerlist.get(i);
										answerBean.setIsFinish("1");
										answerDao.update(answerBean);
									}
								} else {
									showToast("没有可提交的");
								}

							}
						} else {
							showToast("没有可提交的");
						}

						ChildTaskActivity.showDialog(TaskDetailActivity.this, sum, success);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				super.onSuccess(t);
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
			}
		});
	}

	private String getSPString() {
		SharedPreferences sp = this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}

	private void upFileIterator() {
		if (upInfos != null && upInfos.size() > 0) {
			UpLoadFileBean bean = upInfos.get(0);
			uploadFiles(taskid, bean.getSubTaskId(), bean.getStempId(), bean.getTaskQuestionId(), bean.getqType(),
					bean.getFileType(), bean.getOrder(), bean.getOtherAnswer(), bean.getFile(), bean.getGps());
		}

	}

}
